package com.lujieni.springbooteasyexcel.controller;

import com.alibaba.excel.EasyExcel;
import com.lujieni.springbooteasyexcel.dao.StudentDao;
import com.lujieni.springbooteasyexcel.dto.StudentExportDTO;
import com.lujieni.springbooteasyexcel.po.StudentPO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：小鹿爱吃鱼
 * @Date: 2025/4/3 15:07
 * @Description:
 */
@RestController
@RequiredArgsConstructor
public class StudentController {

    private final StudentDao studentDao;

    //数据导出接口
    @GetMapping("/export")
    public void doExport(HttpServletResponse response) throws IOException, IOException {
        //从数据库获取数据
        List<StudentExportDTO> data = new ArrayList<>();
        studentDao.selectAll().forEach(e->{
            StudentExportDTO target = new StudentExportDTO();
            BeanUtils.copyProperties(e,target);
            data.add(target);
        });
        //设置响应头
        response.setHeader("Content-Disposition", "attchment;filename=" + URLEncoder.encode("学生列表.xlsx", "UTF-8"));
        // 设置文本内省
        response.setContentType("application/vnd.ms-excel");
        // 设置字符编码
        response.setCharacterEncoding("utf-8");
        //将数据写入Excel
        EasyExcel.write(response.getOutputStream(), StudentExportDTO.class)
                .sheet("学生列表")
                .doWrite(data);
    }




}
